import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem';
import './style.css';
import axios from 'axios';

class TodoList extends Component {
  //当组件的state或者props发生改变的时候，render函数就会重新执行
  constructor(props) {
    super(props)

    this.state = {
      inputValue: '',
      list: []
    }
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleBtnClick = this.handleBtnClick.bind(this)
    this.handleItemDelete = this.handleItemDelete.bind(this)
  }

  render() {
    return (
      <Fragment>
        <div>
          <input
            className='input'
            value={this.state.inputValue}
            onChange={this.handleInputChange}/>
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul>
          {this.getTodoItem()}
        </ul>
      </Fragment>
    )
  }

  componentDidMount() {
    //ajax请求放在这里，永远不会有问题，只执行一次就可以
    axios.get('/app/js')
    .then((res) => {
      console.log(res.data);
      this.setState(() => ({
        list: res.data
      }));
    })
    .catch((res) => {console.log(res);})
  }

  getTodoItem() {
    return this.state.list.map((item, index) => {
      return (
        <TodoItem
                content={item}
                index={index}
                key={index}
                deleteItem={this.handleItemDelete}
                />
      )
    })
  }

  handleInputChange(e) {
    const value = e.target.value;
    this.setState(() => ({ //es6的简写 写成函数、变成异步
      inputValue: value
    }))
  }

  handleBtnClick() {
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue], //展开运算符
      inputValue: ''
    }))
  }
  //immutable 
  //state 不允许我们做任何的改变，修改副本后重新赋值
  handleItemDelete(index) {
    this.setState((prevState) => {
      const list = [...prevState.list]
      list.splice(index, 1)
      return {
        list
      }
    })
  }
}

export default TodoList;